package master

import (
	"context"
	"crontab/common"
	"fmt"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
	"time"
)

type LogMgr struct {
	client     *mongo.Client
	logCollect *mongo.Collection
}

var (
	G_LogMgr *LogMgr
)

func InitLogMgr() (err error) {
	var (
		client *mongo.Client
		ctx    context.Context
	)
	if client, err = mongo.NewClient(options.Client().ApplyURI(G_Config.DbUrl)); err != nil {
		return
	}
	ctx, _ = context.WithTimeout(context.TODO(), time.Duration(G_Config.DbConnectTimeout)*time.Millisecond)
	if err = client.Connect(ctx); err != nil {
		return
	}
	G_LogMgr = &LogMgr{
		client:     client,
		logCollect: client.Database(G_Config.DbName).Collection(G_Config.TableName),
	}
	return
}

//查看日志
func (logMgr *LogMgr) ListLog(jobName string, skip, limit int) (logArr []*common.JobLog, err error) {
	var (
		filter  *common.LogFilter
		logSort *common.LogSortRule
		opts    *options.FindOptions
		cursor  *mongo.Cursor
		jobLog  *common.JobLog
	)
	logArr = make([]*common.JobLog, 0)
	filter = &common.LogFilter{
		JobName: jobName,
	}
	//按照任务日期进行时间倒序
	logSort = &common.LogSortRule{
		StartTime: -1,
	}

	opts = &options.FindOptions{}
	opts.SetLimit(int64(limit))
	opts.SetSkip(int64(skip))
	opts.SetSort(logSort)
	if cursor, err = logMgr.logCollect.Find(context.TODO(), filter, opts); err != nil {
		return
	}
	defer cursor.Close(context.TODO())

	for cursor.Next(context.TODO()) {
		jobLog = &common.JobLog{}
		if err = cursor.Decode(jobLog); err != nil {
			continue
		}

		logArr = append(logArr, jobLog)
		fmt.Println(logArr)
	}
	return
}
